package com.xliu.csopenproject.pim_server.controller;

import com.xliu.csopenproject.pim_server.controller.io.ImagePresentRequest;
import com.xliu.csopenproject.pim_server.result.Result;
import com.xliu.csopenproject.pim_server.service.ImageService;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
@RequestMapping("/image")
public class ImageController {

    private final ImageService imageService;

    public ImageController(ImageService imageService) {
        this.imageService = imageService;
    }

    @PostMapping("/upload")
    public Result<Void> uploadOneImage(MultipartFile file) {
        try {
            imageService.upload(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }

    @PostMapping("/upload/zip")
    public void uploadImagesZip() {

    }

    @GetMapping("/download")
    public void downloadOneImage(@RequestParam String fileId, HttpServletResponse response) {
        try (OutputStream outputStream = response.getOutputStream();
             InputStream inputStream = imageService.download(fileId)) {
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    // 将多个文件以 zip 包的形式下载
    @PostMapping("/download/zip")
    public void downloadImagesZip() {

    }


    // 展示图片
    public Result<Void> present(ImagePresentRequest request) {

        return Result.success();
    }

}
